//+--------------------------------------------------------------------
//| Copyright(c) 2012 - an.vuongngocduy					
//| This file is a part of Compact Game Engine (CGE)	
//+--------------------------------------------------------------------
#include "cgeCanvasWin.h"
#include "cgePainterOgl.h"

namespace cge
{
	/*----------------------------------------------------------------------------------------*/
	CanvasWin::CanvasWin()
	{
		mWinHandle = null;
		mDevContext = null;
	}
	
	/*----------------------------------------------------------------------------------------*/
	CanvasWin::~CanvasWin()
	{
	}

	/*----------------------------------------------------------------------------------------*/
	void CanvasWin::Setup(const String& caption, const Vector2u& position, const Size2u& dimension)
	{
		mWinRect.Set(position, dimension);

		HINSTANCE hInstance = GetModuleHandle(null);

		Size2u sz = mWinRect.Size();

		RECT rect = { 0, 0, sz.Width, sz.Height };

		AdjustWindowRectEx(&rect, WS_OVERLAPPEDWINDOW, false, 0);

		WNDCLASSEX wndClass = 
		{
			sizeof(WNDCLASSEX),
			CS_OWNDC | CS_HREDRAW | CS_VREDRAW,
			WindowProc,
			0, 0,
			hInstance,
			LoadIcon(null, IDI_APPLICATION),
			LoadCursor(null, IDC_ARROW),
			(HBRUSH)(COLOR_WINDOW + 1),
			null,
			TEXT("Compact Game Engine"),
			LoadIcon(null, IDI_APPLICATION)
		};

		if(!RegisterClassEx(&wndClass)) return;
		
		mWinHandle = CreateWindowEx
		(
			WS_EX_LEFT,
			TEXT("Compact Game Engine"), 
			TEXT(""),
			WS_OVERLAPPEDWINDOW,
			CW_USEDEFAULT, CW_USEDEFAULT,
			rect.right, rect.bottom,
			null, null, hInstance, null
		);

		if(!mWinHandle) return;

		mDevContext = GetDC(mWinHandle);

		mPainter = new PainterOgl();
		mPainter->Initialize(this);

		SetWindowLong(mWinHandle, GWL_USERDATA, (LONG)this);
	}

	/*----------------------------------------------------------------------------------------*/
	void CanvasWin::Show()
	{
		UpdateWindow(mWinHandle);
		ShowWindow(mWinHandle, SW_SHOW);
	}

	/*----------------------------------------------------------------------------------------*/
	void CanvasWin::DistributeMessage()
	{
		MSG wndMsg;
		while(PeekMessage( &wndMsg, mWinHandle, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&wndMsg);
			DispatchMessage(&wndMsg);
		}
	}

	/*----------------------------------------------------------------------------------------*/
	LRESULT CALLBACK CanvasWin::WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
	{
		CanvasWin* cw = (CanvasWin*)GetWindowLong(hWnd, GWL_USERDATA);
	
		switch(uMsg)
		{
		case WM_CLOSE:
			PostQuitMessage(0);
			return 0;
			
		case WM_SIZE:
			return 0;

		case WM_MOVE:
			return 0;

		case WM_PAINT:
			return 0;

		default:
			return DefWindowProc(hWnd, uMsg, wParam, lParam);
		
		}
		return 0;
	}
}